#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <windows.h>  

int main() {
    system("chcp 65001 > nul");
    LARGE_INTEGER frequency, start, end;
    double pi = 0;
    double count = 1;
    double flag = 1;
    double last_pi = 0;
    QueryPerformanceFrequency(&frequency);
    qpc(&start);
    while (1) 
    {
        double term = (1.0 / count) * flag;
        pi += term;
        if (fabs(pi - last_pi) < (1e-10)) break;
        last_pi = pi;
        flag = -flag;
        count += 2;
    }
    qpc(&end);
    double elapsed_time = (double)(end.QuadPart - start.QuadPart) / frequency.QuadPart;
    printf("计算耗时: %.15f 秒\n", elapsed_time);
    printf("π的近似值: %.15f\n", 4 * pi);
    return 0;
}


//上面是莱布尼茨算法，下面是高斯-勒让德算法  上面独立完成，下面是真不会，在csdn上面copy了一份


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <windows.h>  

double factorial(int n) {
    double result = 1.0;
    for (int i = 2; i <= n; i++) 
        result *= i;
    return result;
}

double c_pi(double t_p) {
    double sum = 0.0;
    double last_pi = 0.0;
    int k = 0;
    double constant = 12.0 / sqrt(640320.0 * 640320.0 * 640320.0);
    while (k < 100) 
    { 
        double nt = factorial(6 * k) * (545140134.0 * k + 13591409.0);
        double dt = factorial(3 * k) * pow(factorial(k), 3) * pow(-640320.0, 3 * k);
        double term = nt / dt;
        sum += term;
        double current_pi = 1.0 / (sum * constant);
        if (k > 0 && fabs(current_pi - last_pi) < t_p) 
        {
            return current_pi;
        }
        last_pi = current_pi;
        k++;
    }
    return 1.0 / (sum * constant);
}
int main() {
    system("chcp 65001 > nul");
    LARGE_INTEGER frequency, start, end;
    double precisions[] = {1e-2, 1e-4, 1e-6, 1e-8, 1e-10, 1e-12, 1e-14};
    int num_tests = sizeof(precisions) / sizeof(precisions[0]);
    QueryPerformanceFrequency(&frequency);
    for (int i = 0; i < num_tests; i++) {
        qpc(&start);
        double pi = c_pi(precisions[i]);
        qpc(&end);
        double elapsed_time = (double)(end.QuadPart - start.QuadPart) / frequency.QuadPart;
        printf("%.0e,%.9f", precisions[i], elapsed_time);
        printf("%.15f\n", pi);
    }
    return 0;
}